<template>
  <div class="material_track">
    <one-title title="要料申请跟踪" @refreshData="refresh">
      <div class="mes_btn">
        <el-button
          v-btn-permission="'requestAgain'"
          @click="requestAgain">
          <i class="iconfont icon-btn_issued"></i>
          重新发起请求
        </el-button>
        <disabled-btn
          v-btn-permission="'edit'"
          :judge="modifyJudge"
          iconClass="iconfont icon-btn_edit"
          btnText="修改"
          @judgeClick="modify"></disabled-btn>
        <disabled-btn
          v-btn-permission="'revoke'"
          :judge="revokeJudge"
          iconClass="iconfont icon-btn_return"
          btnText="撤销"
          btnType="success"
          @judgeClick="revoke"></disabled-btn>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <mes-search-comp
        :searchList="tableColConfig"
        ref="mesSearch"
        :searchResult="searchResult"
        @searchInfo="_info">
      </mes-search-comp>
      <div class="table_container">
        <el-table
          border
          stripe
          ref="mesTable"
          v-loading="isLoading"
          element-loading-text="数据加载中"
          style="width: 100%"
          :data="listData.list"
          :max-height="tableMaxHeight"
          :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
          @row-click="row => $refs.mesTable.toggleRowSelection(row)"
          @sort-change="_sort"
          @selection-change="handleSelectionChange"
          @filter-change="handleFilterChange">
          <el-table-column
            type="selection"
            width="40"
            align="center">
          </el-table-column>
          <mes-col-comp
            :key="column.prop"
            v-for="column in tableColConfig"
            :column="column"></mes-col-comp>
          <el-table-column
            label="操作"
            :resizable="false"
            min-width="160"
            fixed="right"
            align="center"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="jump_item" @click.stop="checkRequiredDetails(scope.row.id)">
                要料明细
              </span>
              <span class="jump_item is_disabled" v-if="isClass(scope.row.materialRequestStatusValue)">
                发料明细
              </span>
              <span class="jump_item" v-else @click.stop="checkDeliveryDetails(scope.row)">
                发料明细
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <mes-pagination
        @updateData="init"
        :currentPage="listData.pageNo"
        :total="listData.count || 0"
        :pageSize="listData.pageSize">
      </mes-pagination>
    </div>
    <modify-date ref="ModifyDate" @refresh="init" :selectData="selectData"></modify-date>
    <required-detail ref="RequiredDetail"></required-detail>
    <delivery-detail ref="DeliveryDetail"></delivery-detail>
  </div>
</template>

<script>
import ModifyDate from './components/ModifyDate'
import RequiredDetail from './components/RequiredDetail'
import DeliveryDetail from './components/DeliveryDetail'
import tableColConfig from './tableColConfig'

// 要料中
const REQUEST = 'Request'
// 配送中
const TRANSIT = 'Transit'
// 已收料
const RECEIVED = 'Received'
// 已撤销
const CANCEL = 'Cancel'
// 待审核
const APPROVED = 'ToBeApproved'

export default {
  name: 'MaterialTrack',
  components: {
    ModifyDate, // 修改希望送达时间
    RequiredDetail, // 要料明细
    DeliveryDetail, // 发料明细
  },
  data() {
    return {
      tableColConfig: tableColConfig, // 列配置
      isLoading: false, // 列表数据加载中
      searchData: {}, // 搜索参数
      searchResult: NaN, // 搜索结果数
      sortData: {}, // 排序参数
      selectData: [], // 选中的数据
    }
  },
  computed: {
    // 列表数据
    listData() {
      return this.$store.state.materialTrack.listData
    },
    // 要料状态
    materialRequestStatus() {
      return this.$store.state.dict.materialRequestStatus.labels || []
    },
    // 验证是否已选
    _selected() {
      if (!this.selectData.length) return {msg: '请选择需要操作的要料清单！'}
    },
    // 修改判断
    modifyJudge() {
      if (this._selected) return this._selected
      if (this.selectData.some(item => item.materialRequestStatusValue !== REQUEST && item.materialRequestStatusValue !== APPROVED)) {
        return {
          msg: '只能修改“要料中”或“待审核”状态的要料清单',
          disabled: true
        }
      }
      return {msg: false}
    },
    // 修改判断
    revokeJudge() {
      if (this._selected) return this._selected
      if (this.selectData.some(item => item.materialRequestStatusValue !== REQUEST && item.materialRequestStatusValue !== APPROVED)) {
        return {
          msg: '只能撤销“要料中”或“待审核”状态的要料清单',
          disabled: true
        }
      }
      return {msg: false}
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    // 列筛选回调
    handleFilterChange(filters) {
      let query = this.$filterParams(this.tableColConfig, filters)
      Object.assign(this.searchData, query.search)
      this.$refs.mesTable.clearSort()
      this.sortData = query.order
      this.init()
    },
    // 显示修改弹框
    modify() {
      this.$refs.ModifyDate.openDialog()
    },
    // 撤销
    revoke() {
      this.mesConfirm('选中的要料单将被撤销, 是否继续?', '撤销提示').then(() => {
        let ids = this.selectData.map(item => item.id)
        this.$store.dispatch('saveData', {
          method: 'post',
          url: 'a/materialrequest/materialRequest/changestatus',
          data: {
            ids: ids.join(','),
            statusId: this.materialRequestStatus.find(item => item.value === CANCEL).id
          },
          noCommit: true
        })
      }).then(() => {
        this.init()
        this.$message({
          type: 'success',
          message: '撤销成功',
          duration: 1500,
          center: true
        })
      })
    },
    // 判断发料明细样式
    isClass(type) {
      switch (type) {
        case TRANSIT:
        case RECEIVED:
          return false
        default:
          return true
      }
    },
    // 刷新方法
    refresh() {
      this.$refs.mesSearch.clean()
      this.$refs.mesTable.clearSort()
      this.$refs.mesTable.clearFilter()
      this.searchData = {}
      this.sortData = {}
      this.init()
    },
    // 初始化
    init(page) {
      this.isLoading = true
      let pageObj = page || {
        pageNo: 1,
        pageSize: this.listData.pageSize || 15
      }
      let postData = {
        method: 'post',
        url: 'a/materialrequest/materialRequest/list',
        data: {
          pageNo: pageObj.pageNo,
          pageSize: pageObj.pageSize,
          // query: this.searchData,
          query: {...this.searchData, viewSource: 2},
          sort: this.sortData,
        },
        module: 'materialTrack',
        state: 'listData'
      }
      this.$store.dispatch('saveData', postData).then((res) => {
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 搜索
    _info(data = {}) {
      this.searchData = data
      this.$refs.mesTable.clearFilter()
      this.$refs.mesTable.clearSort()
      this.sortData = {}
      this.init()
    },
    // 复选框选中
    handleSelectionChange(val) {
      this.selectData = val
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    // 查看要料明细
    checkRequiredDetails(id) {
      this.$refs.RequiredDetail.openDialog(id)
    },
    // 查看发料明细
    checkDeliveryDetails(row) {
      // 如果是配送中或已收料则显示发料明细
      if (row.materialRequestStatusValue === TRANSIT || row.materialRequestStatusValue === RECEIVED) {
        this.$refs.DeliveryDetail.openDialog(row.id, '发料明细')
      }
    },
    // 重新发起请求
    requestAgain() {
      this.isLoading = true
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/materialrequest/materialRequest/allmaterialrequestagain',
        noCommit: true
      }).then(() => {
        this.tipMessage('success', '发起成功')
        this.init()
      }).finally(() => {
        this.isLoading = false
      })
    },
    /**
     * 提示
     * @param type 提示类型
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style scoped lang="less">
  .material_track {
    .modify_label {
      margin-right: 20px;
    }
  }
</style>
